package com.ruoyi.blog.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.blog.domain.BlogCategory;
import com.ruoyi.blog.domain.BlogLabel;
import com.ruoyi.blog.domain.vo.BlogLabelVo;
import com.ruoyi.blog.service.BlogArticleLabelService;
import com.ruoyi.blog.service.IBlogCategoryService;
import com.ruoyi.blog.service.IBlogLabelService;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.ruoyi.blog.domain.bo.BlogArticleBo;
import com.ruoyi.blog.domain.vo.BlogArticleVo;
import com.ruoyi.blog.domain.BlogArticle;
import com.ruoyi.blog.mapper.BlogArticleMapper;
import com.ruoyi.blog.service.IBlogArticleService;

import java.util.List;
import java.util.Map;
import java.util.Collection;
import java.util.Set;
import java.util.stream.Collectors;


/**
 * 博客文章Service业务层处理
 *
 * @author ruoyi
 * @date 2023-10-01
 */
@RequiredArgsConstructor
@Service
public class BlogArticleServiceImpl extends ServiceImpl<BlogArticleMapper, BlogArticle> implements IBlogArticleService {

    private final BlogArticleMapper baseMapper;
    private final IBlogCategoryService blogCategoryService;
    private final BlogArticleLabelService blogArticleLabelService;
    private final IBlogLabelService blogLabelService;

    /**
     * 查询博客文章
     */
    @Override
    public BlogArticleVo queryById(String articleId){
        BlogArticleVo blogArticleVo = baseMapper.selectVoById(articleId);
        blogArticleVo.setLabelIds(blogLabelService.getArticleLabels(blogArticleVo)
            .stream().map(l -> l.getLabelId()).collect(Collectors.toList()));
        return blogArticleVo;
    }

    /**
     * 查询博客文章列表
     */
    @Override
    public TableDataInfo<BlogArticleVo> queryPageList(BlogArticleBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<BlogArticle> lqw = buildQueryWrapper(bo);
        Page<BlogArticleVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        setArticleCategory(result.getRecords());
        setArticleLabel(result.getRecords());
        return TableDataInfo.build(result);
    }

    /**
     * 设置博客文章对应的分类
     */
    public void setArticleCategory(List<BlogArticleVo> list) {

        Map<Long, BlogCategory> categoryMap = CollStreamUtil.toIdentityMap(blogCategoryService
            .lambdaQuery()
            .select(
                BlogCategory::getCategoryName,
                BlogCategory::getCategoryId,
                BlogCategory::getParentId
            )
            .list(), BlogCategory::getCategoryId);

        if (categoryMap.isEmpty()){
            return;
        }

        for (BlogArticleVo n : list) {
            BlogCategory blogCategory = categoryMap.get(n.getCategoryId());
            if (blogCategory.getParentId() == 0){
                n.setCategoryName(blogCategory.getCategoryName());
            }else {
                n.setCategoryName(categoryMap
                    .get(blogCategory.getParentId()).getCategoryName()
                    + " / " + blogCategory.getCategoryName());
            }
        }

    }

    /**
     * 设置博客文章对应的标签
     */
    public void setArticleLabel(List<BlogArticleVo> list) {
        list.forEach(n -> {
            List<BlogLabelVo> labels =  blogLabelService.getArticleLabels(n);
            List<Long> labelIds = labels.stream().map(l -> l.getLabelId()).collect(Collectors.toList());
            n.setLabelIds(labelIds);
            n.setLabels(labels);
        });
    }


    /**
     * 查询博客文章列表
     */
    @Override
    public List<BlogArticleVo> queryList(BlogArticleBo bo) {
        LambdaQueryWrapper<BlogArticle> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<BlogArticle> buildQueryWrapper(BlogArticleBo bo) {

        List<Long> categoryIds = null;

        if (bo.getCategoryId() != null){
            categoryIds = blogCategoryService.getAllIdByParent(bo.getCategoryId());
        }

        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<BlogArticle> lqw = Wrappers.lambdaQuery();
        lqw.in(categoryIds != null, BlogArticle::getCategoryId, categoryIds);
        lqw.like(StringUtils.isNotBlank(bo.getTitle()), BlogArticle::getTitle, bo.getTitle());
        lqw.like(StringUtils.isNotBlank(bo.getContext()), BlogArticle::getContext, bo.getContext());
        lqw.eq(bo.getTopping() != null, BlogArticle::getTopping, bo.getTopping());
        lqw.eq(bo.getBrowse() != null, BlogArticle::getBrowse, bo.getBrowse());
        lqw.eq(bo.getIsShow() != null, BlogArticle::getIsShow, bo.getIsShow());
        return lqw;
    }

    /**
     * 新增博客文章
     */
    @Override
    public Boolean insertByBo(BlogArticleBo bo) {
        BlogArticle add = BeanUtil.toBean(bo, BlogArticle.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        blogArticleLabelService.updateArticleLabel(add.getArticleId(), bo.getLabelIds());
        if (flag) {
            bo.setArticleId(add.getArticleId());
        }
        return flag;
    }

    /**
     * 修改博客文章
     */
    @Override
    public Boolean updateByBo(BlogArticleBo bo) {
        BlogArticle update = BeanUtil.toBean(bo, BlogArticle.class);
        validEntityBeforeSave(update);
        blogArticleLabelService.updateArticleLabel(update.getArticleId(), bo.getLabelIds());
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(BlogArticle entity){
        //TODO 做一些数据校验,如唯一约束
        List<BlogArticle> list = lambdaQuery().eq(BlogArticle::getTitle,
            entity.getTitle()).list();
        if (list.size() == 1 && entity.getArticleId() == null ||
        list.size() == 1 && !list.get(0).getArticleId().equals(entity.getArticleId())){
            throw new ServiceException("标题已存在");
        }
    }

    /**
     * 批量删除博客文章
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<String> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }
}
